$(function () {


  var weather = localStorage.getItem("weather");
  //获取存储的时间戳

  if (weather) {
    var wather_json = JSON.parse(weather);
    var weatherTime = JSON.parse(weather).time;
  }
  //每个小时刷新
  if (weather && new Date().getTime() - weatherTime < 1000 * 60 * 60 * 1) {
    // 不需要请求了，直接显示存储的数据
    var wather_json = JSON.parse(weather);

    $('.weather').prepend(wather_json.str);
  } else {
    // 没有存储数据，那么就去请求
    $.ajax({
      'url': 'http://wthrcdn.etouch.cn/weather_mini?citykey=101280101',
      'type': 'get', // post
      'dataType': "jsonp", // 数据请求类型
      'success': function (data) {
        // 请求成功后，执行这个回调函数
        console.log(data);
        if (data.status == 1000) {
          //实时温度
          var wendu = data.data.wendu;
          //当天时间
          var currentTime = data.data.forecast[0].date;
          //温度范围
          var temperature = data.data.forecast[0].low + data.data.forecast[0].high;
          //天气
          var weather = data.data.forecast[0].type;
          //风向
          var fengxiang = data.data.forecast[0].fengxiang;
          //风力  <![CDATA[3级]]>
          var fengli = data.data.forecast[0].fengli;
          //截取风力
          fengli = fengli.match(/CDATA\[(\S*)\]\]/)[1];
          //城市
          var currentCity = data.data.city;
          // var str = `
          //     <div class="temperature">${wendu}<span>℃<span></div>
          //     <div class="weather-info">
          //         <P>${currentTime}</P>
          //         <P>${currentCity} ${temperature}</P>
          //         <P>${wind}</P>
          //     </div>
          //     <div class="weather-img">
          //         <img src="${weatherImg}" alt="">
          //             ${weather}
          //     </div>`;
          var str = `
                        <div class="temperature">${wendu}<span>℃<span></div>
                        <div class="weather-info">
                            <P>${currentTime}</P>
                            <P>${currentCity} ${temperature}</P>
                            <P>${fengxiang} ${fengli}</P>
                        </div>
                        <div class="weather-img">
                                ${weather}
                        </div>`;
          $('.weather').prepend(str);
          console.log(str);
          var json = {
            'str': str,
            'time': new Date().getTime() // 记录的当前时间戳
          }
          // console.log(json);
          var json_str = JSON.stringify(json);
          //存储起来
          localStorage.setItem("weather", json_str);
        }
      }
    });
  }
})